package com.woniuxy.kaer.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.kaer.user.model.UserLog;
import com.woniuxy.kaer.user.mapper.UserLogMapper;
import com.woniuxy.kaer.user.service.UserLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sun
 * @since 2025年02月17日
 */
@Service
public class UserLogServiceImpl extends ServiceImpl<UserLogMapper, UserLog> implements UserLogService {
    @Resource
    private UserLogMapper userLogMapper;
    @Override
    public void addUserLog(Integer userId, HttpServletRequest request) throws Exception {
        QueryWrapper<UserLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        UserLog userLog = userLogMapper.selectOne(queryWrapper);
        userLog.setUserLogId(userLog.getUserLogId());
        userLog.setUserId(userId);
        userLog.setLoginTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.systemDefault()));
        userLog.setUserIp(request.getHeader("X-Forwarded-For") != null ? request.getHeader("X-Forwarded-For").split(",")[0].trim() : request.getRemoteAddr());
    }

    @Override
    public UserLog getUserLog(Integer userId) throws Exception {
        UserLog userLog = userLogMapper.selectById(userId);
        return userLog;
    }
}
